package com.watchme.license.verify;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.prefs.Preferences;

import de.schlichtherle.license.CipherParam;
import de.schlichtherle.license.DefaultCipherParam;
import de.schlichtherle.license.DefaultKeyStoreParam;
import de.schlichtherle.license.DefaultLicenseParam;
import de.schlichtherle.license.KeyStoreParam;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseParam;

/**
 * VerifyLicense
 * 
 * @author melina
 */
public class VerifyLicense {
	private static String propertiesPath = "verifyparam.properties";
	// common param
	private String PUBLICALIAS = "";
	private String STOREPWD = "";
	private String SUBJECT = "";
	private String licPath = "";
	private String pubPath = "";

	public void setParam() throws IOException {
		//
		Properties prop = new Properties();

		InputStream in = null;
		try {
			in = VerifyLicense.class.getClassLoader().getResourceAsStream(propertiesPath);

			// InputStream in = new FileInputStream(propertiesPath);
			prop.load(in);
			PUBLICALIAS = prop.getProperty("PUBLICALIAS");
			STOREPWD = prop.getProperty("STOREPWD");
			SUBJECT = prop.getProperty("SUBJECT");
			licPath = prop.getProperty("licPath");
			pubPath = prop.getProperty("pubPath");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}

	public boolean verify(Map<String, String> map) throws Exception {
		// return true;

		LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParams());
		// install license file
		try {
			String url = this.getClass().getClassLoader().getResource(licPath).getPath();
			licenseManager.install(new File(url), map);
			System.out.println("License file instal successfully!");
		} catch (Exception e) {
			// e.printStackTrace();
			String moreInfo = "License file instal failure";
			System.out.println(moreInfo);
			throw e;
		}
		// verify license file
		try {
			licenseManager.verify(map);
			System.out.println("License file verify successfully!");
		} catch (Exception e) {
			// e.printStackTrace();
			String moreInfo = "License file verify failure";
			System.out.println(moreInfo);
			throw e;
		}
		return true;
	}

	//
	private LicenseParam initLicenseParams() {
		Preferences preference = Preferences.userNodeForPackage(VerifyLicense.class);
		CipherParam cipherParam = new DefaultCipherParam(STOREPWD);

		KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(VerifyLicense.class, pubPath, PUBLICALIAS, STOREPWD, null);
		LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT, preference, privateStoreParam, cipherParam);
		return licenseParams;
	}
}